import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '@/store'

const routes = [
  {
    path: '/login',
    component: () => import('@/views/Login/index.vue'),
  },
  {
    path: '/',
    component: () => import('@/views/LayOut/index.vue'),
    redirect: '/user',
    children: [
      {
        path: '/user',
        meta: { title: '用户管理' },
        component: () => import('@/views/user/index.vue'),
      },
      {
        path: '/role',
        meta: { title: '角色管理' },
        component: () => import('@/views/role/index.vue'),
      },
      {
        path: '/menu',
        meta: { title: '菜单管理' },
        component: () => import('@/views/menu/index.vue'),
      },
      {
        path: '/source',
        meta: { title: '资源管理' },
        component: () => import('@/views/source/index.vue'),
      },
    ],
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  const token = useUserStore().token

  const whileList = ['/login', '/404']

  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    if (whileList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
router.afterEach(() => {})

export {router, routes}
